package com.longge.websocket.util;

import java.io.IOException;
import java.util.Date;
import java.util.Optional;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.alibaba.fastjson.JSONObject;
import com.longge.websocket.dto.ServerTextMessage;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyMessageSenderUtils {

	public static boolean sendTextMsgToUser(String sender, String toUser, @NonNull String msg) {
		Optional<WebSocketSession> op = MySessionUtils.getSession(toUser);
		if (op.isPresent()) {
			try {
				String message = JSONObject.toJSONString(ServerTextMessage.builder().message(msg).sender(sender).privateChat(true).time(new Date()).build());
				TextMessage tm = new TextMessage(message);
				op.get().sendMessage(tm);
				return true;
			} catch (IOException e) {
				log.error("send text msg to user:" + toUser + " error", e);
			}
		} else {
			log.warn("user:{} is not inline", toUser);
		}
		return false;
	}


	public static void sendTextMsgToAll(@NonNull String sender, @NonNull String msg) {
		String message = JSONObject.toJSONString(ServerTextMessage.builder().message(msg).sender(sender).time(new Date()).build());
		MySessionUtils.getAllSession().stream().parallel().forEach(item -> {
			sendTextMsg(item.getSession(), message);
		});
	}
	
	public static void sendTextMsgToOther(@NonNull String sender, @NonNull String msg) {
		String message = JSONObject.toJSONString(ServerTextMessage.builder().message(msg).sender(sender).time(new Date()).build());
		MySessionUtils.getCacheSession().entrySet().stream().parallel().forEach(item -> {
			if(!item.getKey().equals(sender)) {
				sendTextMsg(item.getValue().getSession(), message);
			}
		});
	}
	
	private static void sendTextMsg(@NonNull WebSocketSession session, @NonNull String msg) {
		try {
			TextMessage tm = new TextMessage(msg);
			session.sendMessage(tm);
		} catch (IOException e) {
			log.error("send text msg error", e);
		}
	}
}
